package com.lgit.Model4.hw04;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientTest {

    public static void main(String[] args) {
        Socket s = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        Scanner sc = null;
        /*System.out.println("请输入用户名: ");
        String name = sc.next();
        System.out.println("请输入用户密码: ");
        String password = sc.next();
        User user = new User(name, password);
        //User user = new User("关羽", "123456");
        UserMessage um = new UserMessage("check", user);*/
        try {
            // 1.创建Socket类型的对象
            s = new Socket("Lenovo-PC", 8686);
            System.out.println("连接服务器成功...");

            // 2.使用输入输出流通信
            oos = new ObjectOutputStream(s.getOutputStream());
            // 将UserMessage对象发送给服务器进行User账号和密码的判断

            sc = new Scanner(System.in);
            System.out.println("请输入用户名: ");
            String name = sc.next();
            System.out.println("请输入用户密码: ");
            String password = sc.next();
            User user = new User(name, password);
            //User user = new User("关羽", "123456");
            UserMessage um = new UserMessage("check", user);
            System.out.println("数据发送中，请稍后...");
            Thread.sleep(6000);
            oos.writeObject(um);
            System.out.println("发生对象数据成功");

            // 接收服务器端发送的判断后的UserMessage对象
            ois = new ObjectInputStream(s.getInputStream());
            UserMessage returnUm = (UserMessage) ois.readObject();

            // 根据题目要求，对服务器发送回来的UserMessage中的类型做判断
            System.out.println("-------------------------------------");
            System.out.println("接收服务器返回数据成功");
            if ("success".equals(returnUm.getType())) {
                System.out.println("恭喜用户" + returnUm.getUser().getName() + "登录成功！");
            } else {
                System.out.println("账号或密码错误，登录失败！");
            }
        } catch (IOException | ClassNotFoundException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭Socket和输入输出流释放相关资源
            if (null != sc) {
                sc.close();
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
